// 在实体详情页面添加可视化
function drawKnowledgeGraph(data) {
    const width = 800;
    const height = 600;

    const svg = d3.select("#graph-container")
        .append("svg")
        .attr("width", width)
        .attr("height", height);

    // 创建力导向图
    const simulation = d3.forceSimulation(data.nodes)
        .force("link", d3.forceLink(data.links).id(d => d.id))
        .force("charge", d3.forceManyBody())
        .force("center", d3.forceCenter(width / 2, height / 2));

    // 绘制连线
    const link = svg.append("g")
        .selectAll("line")
        .data(data.links)
        .enter().append("line")
        .attr("stroke-width", 2);

    // 绘制节点
    const node = svg.append("g")
        .selectAll("circle")
        .data(data.nodes)
        .enter().append("circle")
        .attr("r", 10)
        .attr("fill", d => d.type === "person" ? "blue" : "green");

    // 添加标签
    const label = svg.append("g")
        .selectAll("text")
        .data(data.nodes)
        .enter().append("text")
        .text(d => d.name)
        .attr("font-size", 12)
        .attr("dx", 15)
        .attr("dy", 4);

    // 更新位置
    simulation.on("tick", () => {
        link
            .attr("x1", d => d.source.x)
            .attr("y1", d => d.source.y)
            .attr("x2", d => d.target.x)
            .attr("y2", d => d.target.y);

        node
            .attr("cx", d => d.x)
            .attr("cy", d => d.y);

        label
            .attr("x", d => d.x)
            .attr("y", d => d.y);
    });
}

// 从API获取数据并渲染
fetch(`/api/knowledge-graph/entity/${entityName}/graph`)
    .then(response => response.json())
    .then(data => drawKnowledgeGraph(data));